package com.czmh.etc.onlinepubsys.services.mingchuang.impl;

import com.alibaba.fastjson.JSON;
import com.czmh.etc.onlinepubsys.constants.RedisKey;
import com.czmh.etc.onlinepubsys.entity.mingchuang.Device;
import com.czmh.etc.onlinepubsys.maper.mingchuang.DeviceMapper;
import com.czmh.etc.onlinepubsys.services.mingchuang.IDeviceService;
import com.czmh.etc.onlinepubsys.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
@Transactional(rollbackFor = Exception.class)
public class DeviceServiceImpl implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private StringRedisTemplate template;

    @Override
    public Device get(String id) {
        Device entity = null;
        String key = RedisKey.DEVICE_KEY + id;
        ValueOperations<String, String> ov = template.opsForValue();
        String val = ov.get(key);
        if (val != null) {
            entity = JSON.parseObject(val.toString(), Device.class);
        } else {
            entity = deviceMapper.selectById(id);
            ov.set(key, JSON.toJSONString(entity));
        }
        return entity;
    }

    @Override
    public List<Device> list() {
        List<Device> list = null;
        Set<String> keys = template.keys(RedisKey.DEVICE_KEY + "*");
        if (keys.size() > 0) {
            list = new ArrayList<>();
            ValueOperations<String, String> ov = template.opsForValue();
            for (String key : keys) {
                String val = ov.get(key);
                Device dv = JSON.parseObject(val, Device.class);
                list.add(dv);
            }
        } else {
            list = deviceMapper.selectList(null);
        }
        return list;
    }

    @Override
    public void saveOrUpdate(Device entity) {
        if (entity.getId() == null) {
            deviceMapper.insert(entity);
        } else {
            deviceMapper.updateById(entity);
        }
        String key = RedisKey.DEVICE_KEY + entity.getId();
        template.opsForValue().set(key, JSON.toJSONString(entity));
    }

    @Override
    public void delete(String id) {
        String key = RedisKey.DEVICE_KEY + id;
        template.delete(key);
        deviceMapper.deleteById(id);
    }
}
